package com.hibiscusking.system.service.impl;

import com.hibiscusking.basic.query.BaseQuery;
import com.hibiscusking.basic.util.PageList;
import com.hibiscusking.system.domain.Menu;
import com.hibiscusking.system.domain.Permission;
import com.hibiscusking.system.domain.Role;
import com.hibiscusking.system.mapper.MenuMapper;
import com.hibiscusking.system.mapper.PermissionMapper;
import com.hibiscusking.system.mapper.RoleMapper;
import com.hibiscusking.system.service.IRoleService;
import com.hibiscusking.basic.service.impl.BaseServiceImpl;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.util.resources.ga.LocaleNames_ga;

import javax.management.Query;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hibiscusking
 * @since 2022-10-24
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public PageList<Role> queryByPage(BaseQuery baseQuery) {
        PageList<Role> queryRole = super.queryByPage(baseQuery);
        List<Role> rows = queryRole.getRows();
        for (Role row : rows) {
            List<Long> menuId = roleMapper.findMenuMiddleByRoleId(row.getId());
            List<Menu> menus = menuMapper.findMenuById(menuId);
            List<Long> permissionsId=  roleMapper.findPermissionMiddleByRoleId(row.getId());
            if (permissionsId.size() > 0) {
                row.setPermissions(permissionsId);
            }
            row.setOwnMenus(menus);
        }
        return queryRole;
    }

    @Override
    public void add(Role role) {
        super.add(role);
        roleMapper.addMiddleMenu(role.getId(),role.getMenus());
        permissionMapper.addMiddlePermission(role.getId(),role.getPermissions());
    }

    @Override
    public void update(Role role) {
        roleMapper.deleMiddleMenu(role.getId());
        roleMapper.deleMiddlePermission(role.getId());
        roleMapper.addMiddleMenu(role.getId(),role.getMenus());
        permissionMapper.addMiddlePermission(role.getId(),role.getPermissions());
    }
}
